# -*- coding: utf-8 -*-
"""
多线程单例
实现线程安全需要配合锁的使用,只有占有锁的线程才能继续访问单例实例
"""

import threading

__all__ = ['Singleton']



def synchronized(func):
    func.__lock__ = threading.Lock()

    def synced_func(*args, **kws):
        with func.__lock__:
            return func(*args, **kws)

    return synced_func


def Singleton(cls):
    instances = {}

    @synchronized
    def get_instance(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]

    return get_instance